package ro.peoplecentric.ctc.common.service.impl;

import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import ro.peoplecentric.ctc.common.dao.ItemDao;
import ro.peoplecentric.ctc.common.entity.Item;
import ro.peoplecentric.ctc.common.exception.ApplicationException;
import ro.peoplecentric.ctc.common.exception.ConcurrentModificationException;
import ro.peoplecentric.ctc.common.service.ItemService;
import ro.peoplecentric.ctc.common.util.ui.ItemCriteria;

/**
 * {@link ItemService} service implementation.
 */
@Service
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = {ApplicationException.class, DataAccessException.class})
public class ItemServiceImpl implements ItemService {

    @Resource
    private ItemDao itemDao;

    @SuppressWarnings("unused")
    @PostConstruct
    private void init() {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void saveItem(Item item) throws ApplicationException {
        itemDao.saveOrUpdate(item);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteItem(Item item) throws ApplicationException {
//		 itemDao.lockForUpdate(item);TODO the lock makes delete throw org.hibernate.NonUniqueObjectException
        Item dbItem = itemDao.getById(Item.class, item.getId());

        if (dbItem == null) {
            //concurent modification exception
            throw new ConcurrentModificationException("The Item[id : " + item.getId() + "] was already deleted");
        }
        itemDao.delete(dbItem);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Item> getAll() {
        return itemDao.getAll();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Item> getLastModifiedItems() throws ApplicationException {
       return itemDao.getLastModifiedItems();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Item> find(ItemCriteria itemCriteria) throws ApplicationException{
       return itemDao.find(itemCriteria);
    }

    @Override
    public Item getById(Long id) throws ApplicationException {
        return itemDao.getById(Item.class, id);
    }

    @Override
    public List<Item> getAllItems(String order, String orderBy) throws ApplicationException {
        return itemDao.getAllItems(order, orderBy);
    }
}
